package com.dongdongshop.controller;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectRequest;
import com.dongdongshop.data.Result;
import com.dongdongshop.enums.ResultEnums;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("file")
public class ImgFile {

    @ResponseBody
    @RequestMapping("upLoadFile")
    public Result upLoadFile(@RequestParam(value = "myFile") MultipartFile myFile) throws IOException {

        String https = "https://";
        // Endpoint以华东1（杭州）为例，其它Region请按实际情况填写。
        String endpoint = "oss-cn-beijing.aliyuncs.com";
        // 阿里云账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维，请登录RAM控制台创建RAM用户。
        String accessKeyId = "LTAI5tDi7DYc2CQQPMe7sqF6";
        String accessKeySecret = "UmQ0yjbfyeObpLW1cGlcfmPGighScz";
        // 填写Bucket名称，例如examplebucket。
        String bucketName = "dk-ggw";
        // 填写Object完整路径，完整路径中不能包含Bucket名称，例如exampledir/exampleobject.txt。
        String objectName = "image/" + myFile.getOriginalFilename();

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build( https + endpoint, accessKeyId, accessKeySecret);
        try {
            InputStream inputStream = myFile.getInputStream();
            // 填写字符串。
//            String content = "Hello OSS";

            // 创建PutObjectRequest对象。
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, objectName, inputStream);

            // 如果需要上传时设置存储类型和访问权限，请参考以下示例代码。
            // ObjectMetadata metadata = new ObjectMetadata();
            // metadata.setHeader(OSSHeaders.OSS_STORAGE_CLASS, StorageClass.Standard.toString());
            // metadata.setObjectAcl(CannedAccessControlList.Private);
            // putObjectRequest.setMetadata(metadata);

            //返回路径
            String fileurl = https + bucketName + "." + endpoint + "/" + objectName;

            // 上传字符串。
            ossClient.putObject(putObjectRequest);
            Map<String, String> url = new HashMap<>();
            url.put("imgUrl", fileurl);
            return Result.response(ResultEnums.UPLIOAD_SUCCESS).setData(url);
        } catch (Exception oe) {
            System.out.println(oe);
            return Result.response(ResultEnums.UPLIOAD_ERROR);
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }
}
